//
//  HMHomeTableViewController.swift
//  01-SinaWeibo
//
//  Created by 周英培 on 16/5/19.
//  Copyright © 2016年 周英培. All rights reserved.
//

import UIKit

import SVProgressHUD
/*
 1.跳转到子控制器隐藏底部tabBar的方法：detatil.hidesBottomBarWhenPushed = true  关键属性：hidesBottomBarWhenPushed

 
 */


 private let HOMECELL = "homecell"


class HMHomeTableViewController: HMBasicTableViewController {
    
    //自定义刷新控件
    let refreshView = HMRefreshControl()
    
    
//    //定义数据源数组
//    var statuses : [HMStatusModel] = [HMStatusModel]()
    
    //添加一个视图模型属性
    lazy var statusListViewModel : HMStatusListViewModel = HMStatusListViewModel()
    

//    var userLogin = false
//    
//    override func loadView() {
//        
//        if userLogin {//如果登录，显示tableView
//            
//            super.loadView()
//            
//        } else {//如果未登录，显示未登录界面
//        
//        loadVisitorLoginView()
//        
//        }
//        
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

    //设置未登录界面
        visitorLoginView.updateUI("visitordiscover_feed_image_smallicon", title: "关注一些人,回到这里看看有什么惊喜",isHome: true)
    
        //设置导航条
        setNavBar()
        
        //这册cell
        prepareTableView()
        
        //请求首页数据
        loadHomePageData()
        
//        tableView.scrollsToTop = true
    }
    
    //这册cell
    private func prepareTableView() {
    
        tableView.registerClass(HMStatusCell.self, forCellReuseIdentifier: HOMECELL)
        
        //设置杭高
//        self.tableView.rowHeight = 160
        
        //跟据 AutoLayout 约束的高度自动计算
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //设置预估行高  行高的自动计算
        //提高tableView加载效率 预估行高 * 数据源的数量 = contentSize  -> tableView才可以滚动
        //设置预估杭高时 需要给cell 的 contView设置底部约束
        tableView.estimatedRowHeight = 300
        
        //取消点击cell的效果
        
        
//        //下拉刷新
//        refreshControl = UIRefreshControl()
        
        //添加刷新响应事件
        //        refreshControl?.addTarget(self, action: #selector(loadHomePageData), forControlEvents: .ValueChanged)
        
        self.tableView.addSubview(refreshView)
        //添加刷新响应事件
        refreshView.addTarget(self, action: #selector(loadHomePageData), forControlEvents: .ValueChanged)
        
        
        //设置小菊花控件为tableView的tableViewFooterView
        tableView.tableFooterView = pullUpView
        
        //添加到导航条上面
        self.navigationController?.navigationBar.addSubview(tipLabel)
    
        //显示在导航条下面
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    
    //懒加载  下拉加载更多数据 小菊花控件
    private lazy var pullUpView : UIActivityIndicatorView = {
    
    let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        
        //初始化的时候做动画
//        indicatorView.startAnimating()
        
        return indicatorView
    
    
    }()
    
    //懒加载 提示数据的label
    private lazy var tipLabel : UILabel = {
    
        let l = UILabel(title: "", font: 15, textColor: UIColor.whiteColor())
        
        //设置背景颜色
        l.backgroundColor = UIColor.orangeColor()
        
        //设置frame
        l.frame = CGRect(x: 0, y: -64, width: ScreenWidth, height: 40)
        
        return l
    
    }()
    
 /*
//    func loadVisitorLoginView() {
//    
//        let v = HMVisitorLoginView()
//        
////        v.backgroundColor = UIColor.greenColor()
//        
//        view = v
//        
//    
//    }
 */
    
    //设置导航条
    private func setNavBar() {
    
        let popItem = UIBarButtonItem(imageName: "navigationbar_pop", title: nil, target: self, action: #selector(puch))
        
    //设置导航条右边的按钮
        navigationItem.rightBarButtonItem = popItem
    }
    
    @objc private func puch() {
    
        let detatil = HMDetailViewController()
        
        //跳转到子控制器时，隐藏tabBar
//        detatil.hidesBottomBarWhenPushed = true
        
        //跳转控制器
        navigationController?.pushViewController(detatil, animated: true)
        
    
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

//MARK:请求首页数据
extension HMHomeTableViewController {

    //请求首页数据
  @objc private func loadHomePageData() {
        
        //回调数据
        statusListViewModel.loadHomePageData(pullUpView.isAnimating()) { (isSuccess,count) in
            
            //停止小菊花的转动
//            self.pullUpView.stopAnimating()
            //停止刷新
//            self.refreshControl?.endRefreshing()
            self.refreshView.endRefreshing()
            
            if !isSuccess {
            
                SVProgressHUD.showErrorWithStatus(commonError)
                
                return
            
            }
            
            if self.pullUpView.isAnimating() {
            
            //静默加载数据
                self.pullUpView.stopAnimating()
            
            }  else {
            
                //下拉刷新数据 提示用户刷新了多少条数据
                self.startAnimation(count)
            
            }
            
            //请求数据成功 刷新数据
            self.tableView.reloadData()
            
        }
        
//        HMNetworkTools.sharedTools.loadHomeData { (responseObject, error) in
//            
//            if error != nil {
//                
//                SVProgressHUD.showErrorWithStatus(commonError)
//                
//                return
//                
//            }
//            
//            //请求回来的网络数据
//            //        print(responseObject)
//            
//            //处理请求回来的网络数据
//            guard let dict = responseObject as? [String : AnyObject] else {
//                
//                return
//                
//            }
//            
//            //打印字典
//            print(dict)
//            
//            //根据字典里面的“statuses”来获取数组
//            guard let array = dict["statuses"] as? [[String : AnyObject]] else {
//                
//                return
//                
//            }
//            
//            //打印数组
//            print(array)
//            
//            //MARK:便利数组 获取字典 然后字典转模型
//            //定义空的可变数组 用来装模型
//            var arrM = [HMStatusModel]()
//            
//            for item in array {
//                
//                //字典转模型
//                let statusM = HMStatusModel(dict: item)
//                
//                //添加到可变数组中
//                arrM.append(statusM)
//                
//            }
//            
//            //赋值
//            self.statuses = arrM
//            
//            //刷新数据
//            self.tableView.reloadData()
//            
//        }
        
    }
    
    //提示用户刷新多少条数据
    private func startAnimation(count:Int) {
    
        let tipCount = (count == 0) ? "没有新数据" : "有\(count)条数新据"
        tipLabel.text = tipCount
        tipLabel.textAlignment = .Center
        
        let rect = tipLabel.frame
        
        UIView.animateWithDuration(0.6, animations: { 
            
            //显示出来
            self.tipLabel.frame = CGRect(x: 0, y: 44, width: ScreenWidth, height: 40)
            
            }) { (_) in
                
                UIView.animateWithDuration(0.3, delay: 1, options: [], animations: { 
                    
                    // 回去
                    self.tipLabel.frame = rect
                    
                    }, completion: { (_) in
                        
                        
                        
                })
                
        }
    
    }

}

//MARK: - Table view data source 实现数据源方法
extension HMHomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.statusViewModelArray.count
    }
    
    
     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
     let cell = tableView.dequeueReusableCellWithIdentifier(HOMECELL, forIndexPath: indexPath) as! HMStatusCell
     
        // 设置数据
//        cell.textLabel?.text = self.statuses[indexPath.row].text
        
        if indexPath.row == statusListViewModel.statusViewModelArray.count - 1 && !pullUpView.isAnimating() {
            
            //加载动画
            pullUpView.startAnimating()
            
            //下拉加载数据
            loadHomePageData()
            
        }
        
        cell.statusViewModel = statusListViewModel.statusViewModelArray[indexPath.row]
        
     return cell
     }
    

}

extension HMHomeTableViewController {

    /*
     // Override to support conditional editing of the table view.
     override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */
    
    /*
     // Override to support editing the table view.
     override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
     if editingStyle == .Delete {
     // Delete the row from the data source
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
     } else if editingStyle == .Insert {
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
     }
     }
     */
    
    /*
     // Override to support rearranging the table view.
     override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
     
     }
     */
    
    /*
     // Override to support conditional rearranging of the table view.
     override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     // Return false if you do not want the item to be re-orderable.
     return true
     }
     */
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
